//
//  HistoryMessage.m
//  MINFOBBS
//
//  Created by juvid on 13-12-9.
//  Copyright (c) 2013年 minfo. All rights reserved.
//

#import "HistoryMessage.h"
#import "DetectionSystemVersion.h"
#import "FeedbackOnLine.h"
#import "HistoryMessageCell.h"
#import "SBJson.h"
@interface HistoryMessage (){
    
}

@end

@implementation HistoryMessage

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self BackButton];
    if (!self.isFeed) {
        self.btnFeed.hidden=YES;
        self.btnClean.frame=CGRectMake(self.btnClean.frame.origin.x, self.btnClean.frame.origin.y, 290, self.btnClean.frame.size.height);
    }
    self.view.backgroundColor=[UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1];
    self.table.layer.cornerRadius=8.0;
    pageLimit=10;
    pageStart=0;
    arrRowHight=[[NSMutableArray alloc]init];
    

    loadMore=[[LoadMore alloc]initWithFrame: CGRectMake(0, 0, 290, 32)];
//    loadMore.frame= CGRectMake(0, 0, 290, 32);
    [self.table addSubview:loadMore];
    self.table.separatorStyle=UITableViewCellSeparatorStyleNone;
    strTime=@"asc";
    [self GetDatas:strTime];
    // Do any additional setup after loading the view from its nib.
}
-(void)BackButton{
    if ([[DetectionSystemVersion alloc]Version]) {
        self.edgesForExtendedLayout=UIRectEdgeNone;
    }
    self.navigationItem.titleView=[DetectionSystemVersion SetBarTitle:@"百事搜"];
    [self.navigationItem setHidesBackButton:YES];
    UIButton *btnBack=[[DetectionSystemVersion alloc]BackButton];
    [btnBack addTarget:self action:@selector(BackReturn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem=backItem;
    
}
#pragma mark 导航栏按钮事件
-(void)BackReturn:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [tRequest clearDelegatesAndCancel];
    [tRequest cancel];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [NSThread cancelPreviousPerformRequestsWithTarget:self];
}
#pragma mark 异步数据请求
-(void)GetDatas:(NSString *)time{
    loadMore.loadingTitle.text=@"正在加载...";
    [loadMore.loadingAni startAnimating];
    if (self.isFeed) {
        tRequest=[[[ScreenAccess alloc]init]ASIOpinionhistory:time Start:pageStart Limit:pageLimit];
    }
    else{
         tRequest=[[[ScreenAccess alloc]init]ASIMessagehistory:pageStart Limit:pageLimit];
    }
    [tRequest setDelegate:self];
    [tRequest setUsername:@"allMessage"];
    
}
-(void)requestFinished:(ASIHTTPRequest*)request{
    
    NSString *response = [request responseString];
    SBJsonParser * parser = [[SBJsonParser alloc] init];
    NSMutableDictionary *Result = [parser objectWithString:response];
    
    if ([request.username isEqual:@"allMessage"]){
        BOOL IsSuccess=[[[Result objectForKey:@"Response"]objectForKey:@"status"]integerValue]==200?YES:NO;
        if (IsSuccess==YES) {
            if (self.isFeed) {
                 total=[[[Result objectForKey:@"Response"]objectForKey:@"hadopinion"] integerValue];
            }
            else{
                 total=[[[Result objectForKey:@"Response"]objectForKey:@"hadmessage"] integerValue];
            }
            if (total==1) {
                if (arrReturn==nil) {
                    arrReturn=[[NSMutableArray alloc]init];
                }
                if (self.isFeed) {
                    [arrReturn addObjectsFromArray:[[Result objectForKey:@"Response"] objectForKey:@"opinions"]];
                    [self SetCellHight:[[Result objectForKey:@"Response"] objectForKey:@"opinions"]];
                }
                else{
                    [arrReturn addObjectsFromArray:[[Result objectForKey:@"Response"] objectForKey:@"messages"]];
                    [self SetCellHight:[[Result objectForKey:@"Response"] objectForKey:@"messages"]];
                }
               
                 loadMore.loadingTitle.text=@"上拉加载更多";
            }
            
            else{
                 loadMore.loadingTitle.text=@"没有更多";
            }
            [loadMore.loadingAni stopAnimating];
        }
    }
    else if([request.username isEqual:@"weather"]){
    }
    loadingmore=NO;
    
}

-(void)requestFailed:(ASIHTTPRequest*)request{
    [loadMore.loadingAni stopAnimating];
    loadMore.loadingTitle.text=@"无网络";
    loadingmore=NO;
    
}
-(void)SetCellHight:(NSArray *)arry{
    CGSize sizeFrame;
       for (int i=0; i<arry.count; i++) {
        NSString *str;
        float totalCount=70.0;
           if (self.isFeed) {
               str=[NSString stringWithFormat:@"       %@",[[arry objectAtIndex:i] objectForKey:@"feedback"]];
               if (str.length!=0) {
                   sizeFrame =[str sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(270, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
                   totalCount+=sizeFrame.height;
                   //            NSLog(@"%@",arrRowHight);
               }
               str=[NSString stringWithFormat:@"       %@",[[arry objectAtIndex:i] objectForKey:@"opinion"]];
               if (str.length!=0) {
                   sizeFrame =[str sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(270, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
                   totalCount+=sizeFrame.height;
                   //            NSLog(@"%@",arrRowHight);
               }

           }
           else{
               totalCount=45.0;
               str=[NSString stringWithFormat:@"       %@",[[arry objectAtIndex:i] objectForKey:@"message"]];
               if (str.length!=0) {
                   sizeFrame =[str sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(270, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
                   totalCount+=sizeFrame.height;
                   //            NSLog(@"%@",arrRowHight);
               }

           }
        [arrRowHight addObject:[NSString stringWithFormat:@"%f",totalCount]];
    }
    [self.table reloadData];
    loadMore.frame=CGRectMake(0, self.table.contentSize.height-35, 320, 32);
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return arrReturn.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"HistoryMessageCell";
    HistoryMessageCell *cell = (HistoryMessageCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell=[[[NSBundle mainBundle]loadNibNamed:CellIdentifier owner:self options:Nil]objectAtIndex:0];
        //        cell.backgroundColor=[UIColor grayColor];
    }
    NSString *str;
    if (self.isFeed) {
        str=str=[NSString stringWithFormat:@"       %@",[[arrReturn objectAtIndex:indexPath.row] objectForKey:@"feedback"]];
        cell.labFeed.text=str;
        CGSize labSize=[DetectionSystemVersion String:str Width:270 Font:13];
        cell.labFeed.frame=CGRectMake(cell.labFeed.frame.origin.x, cell.labFeed.frame.origin.y, 255, labSize.height);
        
        cell.labOhter.frame=CGRectMake(cell.labOhter.frame.origin.x, cell.labFeed.frame.origin.y+cell.labFeed.frame.size.height +5, 275,cell.labOhter.frame.size.height);
        str=[NSString stringWithFormat:@"       %@",[[arrReturn objectAtIndex:indexPath.row] objectForKey:@"opinion"]];
        labSize=[DetectionSystemVersion String:str Width:270 Font:13];
        
        cell.labAnswer.frame=CGRectMake(cell.labAnswer.frame.origin.x, cell.labOhter.frame.origin.y+cell.labOhter.frame.size.height +5, 275, labSize.height);
        cell.labAnswer.text=str;
        //    cell.accessoryView=lab;
        //    cell.textLabel.font=[UIFont systemFontOfSize:15];
        cell.labTime=[[arrReturn objectAtIndex:indexPath.row] objectForKey:@"sendtime"];

    }
    else{
        [cell.labAnswer removeFromSuperview];
        [cell.labOhter removeFromSuperview];
        str=str=[NSString stringWithFormat:@"       %@",[[arrReturn objectAtIndex:indexPath.row] objectForKey:@"message"]];
        cell.labFeed.text=str;
        CGSize labSize=[DetectionSystemVersion String:str Width:270 Font:13];
        cell.labFeed.frame=CGRectMake(cell.labFeed.frame.origin.x, cell.labFeed.frame.origin.y, 255, labSize.height);

    }
    [cell.btnDelete addTarget:self action:@selector(PressDelete:) forControlEvents:UIControlEventTouchUpInside];
    cell.btnDelete.tag=510+indexPath.row;
    
//    }
    
    
    return cell;
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    float rowHight = 0.0;
    if (arrRowHight.count>0) {
        rowHight=[[arrRowHight objectAtIndex:indexPath.row] floatValue];
    }
    return rowHight;

}
-(float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 35;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *result;
    result=[[UIView alloc]init];
    result.backgroundColor=[UIColor clearColor];
    return result;
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (total==1) {
        PrevCGPoint=scrollView.contentOffset;
        if (PrevCGPoint.y>scrollView.contentSize.height-scrollView.frame.size.height) {
            if (loadingmore) return;
            loadingmore = YES;
            pageStart++;
            [self GetDatas:strTime];
        }
    }
    
}
-(void)PressDelete:(UIButton *)button{
    longIndexPath=[NSIndexPath indexPathForRow:button.tag-510 inSection:0];
    [arrReturn removeObjectAtIndex:longIndexPath.row];
   
    [arrRowHight removeObjectAtIndex:longIndexPath.row];
    [self.table deleteRowsAtIndexPaths:[NSArray arrayWithObject:longIndexPath] withRowAnimation:UITableViewRowAnimationBottom];
    
//    [self.table reloadData];
}
- (IBAction)PressClean:(id)sender {
    [arrRowHight removeAllObjects];
    [arrReturn removeAllObjects];
    total=0;
    [self.table reloadData];
}
- (IBAction)PressFeed:(id)sender {
    FeedbackOnLine *feedBack=[[FeedbackOnLine alloc]init];
    [self.navigationController pushViewController:feedBack animated:YES];
}

- (IBAction)PressTime:(UIButton *)sender {
    arrReturn=Nil;
    arrRowHight=[[NSMutableArray alloc]init];
    pageStart=0;
    if ([strTime isEqual:@"asc"]) {
        strTime=@"desc";
        [sender setTitle:@"   时间排序  ↓" forState:UIControlStateNormal];
    }
    else{
        strTime=@"asc";
        [sender setTitle:@"   时间排序  ↑" forState:UIControlStateNormal];

    }
     [self GetDatas:strTime];
}
@end
